package com.blacktea.webmagic.demo.strategy.download;

import cn.hutool.core.io.IoUtil;
import com.blacktea.webmagic.demo.condiction.DownloadBrowseCondiction;
import com.blacktea.webmagic.demo.constant.FileTypeConstant;
import com.blacktea.webmagic.demo.domain.BrowseDownload;
import com.blacktea.webmagic.demo.domain.Download;
import com.blacktea.webmagic.demo.strategy.DownloadStrategy;
import com.blacktea.webmagic.demo.util.WebMagicUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * @description:
 * @author: black tea
 * @date: 2021/9/26 14:28
 */
@Slf4j
public class DownloadBrowseStrategy implements DownloadStrategy {

    @Override
    public void check(Download download) {
        new DownloadBrowseCondiction()
                .check((BrowseDownload) download);
    }

    @Override
    public void downloadMD(String pathorName, HttpServletResponse response, String html) {
        try {
            FileTypeConstant.FileTypeEnum md = FileTypeConstant.FileTypeEnum.MD;
            byte[] bytes = html.getBytes(StandardCharsets.UTF_8);
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(pathorName, "UTF-8"));
            response.addHeader("Content-Length", "" + bytes.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType(md.getContentType());
            toClient.write(bytes);
            toClient.flush();
            toClient.close();
            log.info("\n当前下载文件{}到浏览器完成。",pathorName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void downloadZip(String pathorName, HttpServletResponse response, Map<String, Map<String, String>> dataMap) {
        // 浏览器下载
        try {
            FileTypeConstant.FileTypeEnum zip = FileTypeConstant.FileTypeEnum.ZIP;
            //创建HttpServerResponse的输出流
            OutputStream out = response.getOutputStream();
            ZipOutputStream zos = new ZipOutputStream(out);
            this.downloadZip(zos,dataMap);
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(pathorName, "UTF-8"));
            out.flush();
            IoUtil.close(zos);
            IoUtil.close(out);
            log.info("\n当前浏览器下载文件{}完成。",pathorName);
        } catch (IOException e) {
            log.error("浏览器下载失败",e);
        }
    }

    @Override
    public void downloadZip(ZipOutputStream zos, Map<String, Map<String, String>> dataMap) {
        WebMagicUtil.writeZosZip2(zos,dataMap);
    }
}
